/*
 * Copyright 2014 Hieu Rocker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rockerhieu.emojicon;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.method.Touch;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.rockerhieu.emojicon.emoji.SerializeManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Hieu Rocker (rockerhieu@gmail.com).
 */
public class EmojiconTextView1 extends TextView {
    private int mEmojiconSize;
    private int mEmojiconTextSize;
    private int mTextStart = 0;
    private int mTextLength = -1;
	private int mEmojiconLines=0;
    private boolean mUseSystemDefault = false;
    Context context;
    
    public EmojiconTextView1(Context context) {
        super(context);
        this.context=context;
        init(null);
    }

    public EmojiconTextView1(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        init(attrs);
    }

    public EmojiconTextView1(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context=context;
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        mEmojiconTextSize = (int) getTextSize();
        if (attrs == null) {
            mEmojiconSize = (int) getTextSize();
//            mEmojiconSize = 55;
        } else {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.Emojicon);
            mEmojiconSize = (int) a.getDimension(R.styleable.Emojicon_emojiconSize, getTextSize());
			mEmojiconLines= a.getInteger(R.styleable.Emojicon_emojiconLines, 0);
//            mEmojiconSize = 55;
            mTextStart = a.getInteger(R.styleable.Emojicon_emojiconTextStart, 0);
            mTextLength = a.getInteger(R.styleable.Emojicon_emojiconTextLength, -1);
            mUseSystemDefault = a.getBoolean(R.styleable.Emojicon_emojiconUseSystemDefault, false);
            a.recycle();
        }
        setText(getText());
    }
	boolean dontConsumeNonUrlClicks = false;
	boolean linkHit;
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		linkHit = false;
		boolean res = super.onTouchEvent(event);

		if (dontConsumeNonUrlClicks)
			return linkHit;
		return res;

	}

	public static class LocalLinkMovementMethod extends LinkMovementMethod{
		static LocalLinkMovementMethod sInstance;


		public static LocalLinkMovementMethod getInstance() {
			if (sInstance == null)
				sInstance = new LocalLinkMovementMethod();

			return sInstance;
		}

		@Override
		public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
			int action = event.getAction();

			if (action == MotionEvent.ACTION_UP ||
					action == MotionEvent.ACTION_DOWN) {
				int x = (int) event.getX();
				int y = (int) event.getY();

				x -= widget.getTotalPaddingLeft();
				y -= widget.getTotalPaddingTop();

				x += widget.getScrollX();
				y += widget.getScrollY();

				Layout layout = widget.getLayout();
				int line = layout.getLineForVertical(y);
				int off = layout.getOffsetForHorizontal(line, x);

				ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);

				if (link.length != 0) {
					if (action == MotionEvent.ACTION_UP) {
						link[0].onClick(widget);
					} else if (action == MotionEvent.ACTION_DOWN) {
						Selection.setSelection(buffer,
								buffer.getSpanStart(link[0]),
								buffer.getSpanEnd(link[0]));
					}

					if (widget instanceof EmojiconTextView1){
						((EmojiconTextView1) widget).linkHit = true;
					}
					return true;
				} else {
					Selection.removeSelection(buffer);
					Touch.onTouchEvent(widget, buffer, event);
					return false;
				}
			}
			return Touch.onTouchEvent(widget, buffer, event);
		}
	}
	public void setText(String html,Intent intent) {
		dontConsumeNonUrlClicks = true;
//		CharSequence sequence = Html.fromHtml(html);
		SpannableStringBuilder strBuilder = new SpannableStringBuilder(html);
		String content = html;
		if (content.equals("")) {
		} else {
			List<String> tempL = SerializeManager.getUrlsInContent(content);
			if(tempL != null){
				for(String temp : tempL){
					int index = content.indexOf(temp);
					strBuilder.setSpan(new URLClickSpan(temp,intent), index, index+temp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				}
			}

			setText(strBuilder);
			setMovementMethod(LocalLinkMovementMethod.getInstance());

		}

	}
    public void setText(String themeContent,String html,Intent intent,Intent intent2) {
//		CharSequence sequence = Html.fromHtml(html);
		List<Integer>mList=getPostation(html,"#");
		SpannableStringBuilder strBuilder = new SpannableStringBuilder(html);
		if(null!=mList&&mList.size()>1){
			int n=mList.size()/2;
			for(int i=0;i<n;i++){
				String sub=html.substring(mList.get(i*2), mList.get(i*2+1)+1);
				URLSpan clickSpan;
				if(themeContent.equals(sub)){
					clickSpan = new NoLineClickSpan(sub,null); //���ó�����
				}else{
					clickSpan = new NoLineClickSpan(sub,intent); //���ó�����
				}
				try {
					if(i==n-1&&i!=0)
						strBuilder.setSpan(clickSpan, mList.get(i*2)-1, mList.get(i*2)+sub.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
					else
						strBuilder.setSpan(clickSpan, mList.get(i*2), mList.get(i*2+1)+1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		setText(strBuilder,null);
//		setMovementMethod(LinkMovementMethod.getInstance());


		String content = html;
		if (content.equals("")) {
		} else {

//		SpannableString ss = new SpannableString(content);
		List<String> tempL = SerializeManager.getUrlsInContent(content);
		if(tempL != null){
		for(String temp : tempL){
		int index = content.indexOf(temp);
		strBuilder.setSpan(new URLClickSpan(temp,intent2), index, index+temp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		}

		setText(strBuilder);
			setMovementMethod(LocalLinkMovementMethod.getInstance());


		/*CharSequence text = getText();
		if (text instanceof Spannable) {
		int end = text.length();
		Spannable sp = (Spannable) getText();
		URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
		SpannableStringBuilder style = new SpannableStringBuilder(text);
		style.clearSpans();// should clear old spans


		// 循环把链接发过去
		for (URLSpan url : urls) {
		MyURLSpan myURLSpan = new MyURLSpan(url.getURL(), myHandler);
		style.setSpan(myURLSpan, sp.getSpanStart(url),
		sp.getSpanEnd(url), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		}
		setText(style);
		}*/
		}
	}
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//    	return false;
//    }

    
    
    @Override
    public void setText(CharSequence text, BufferType type) {
        if (!TextUtils.isEmpty(text)) {
            SpannableStringBuilder builder = new SpannableStringBuilder(text);
            EmojiconHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);
            text = builder;
        }
        
        super.setText(text, type);
    }
	/**
	 * 注意：spannableString 设置Spannable 的对象到spannableString中时，要用Spannable.SPAN_EXCLUSIVE_EXCLUSIVE的flag值，不然可能会会出现后面的衔接字符串不会显示
	 */
	@Override
	protected void onDraw(Canvas canvas) {
		CharSequence charSequence = getText() ;
		if(mEmojiconLines>0&&this.getLineCount()>mEmojiconLines){
		int lastCharDown = getLayout().getLineVisibleEnd(mEmojiconLines-1) ;
			if (charSequence.length() > lastCharDown){
				SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder() ;
				spannableStringBuilder.append(charSequence.subSequence(0,lastCharDown-4)).append("...") ;
				setText(spannableStringBuilder);
			}
		}
		super.onDraw(canvas);
	}
	private class NoLineClickSpan extends URLSpan {
		String text;
		Intent intent;
		public NoLineClickSpan(String text,Intent intent) {
		    super(text);
		    this.text = text;
		    this.intent=intent;
		}

		@Override
		public void updateDrawState(TextPaint ds) {
		    ds.setColor(Color.parseColor("#f55857"));
		    ds.setUnderlineText(false); //ȥ���»���
		}

		@Override
		public void onClick(View widget) {
		    //���������ʱ����
			if(null!=intent){
				intent.putExtra("content", text);
				context.startActivity(intent);
			}
		}
	}
    private class URLClickSpan extends URLSpan {
		String text;
		Intent intent;
		public URLClickSpan(String text,Intent intent) {
		    super(text);
		    this.text = text;
		    this.intent=intent;
		}

		@Override
		public void updateDrawState(TextPaint ds) {
		    ds.setColor(Color.parseColor("#f55857"));
		    ds.setUnderlineText(false); //ȥ���»���
		}

		@Override
		public void onClick(View widget) {
		    //���������ʱ����
			if(null!=intent){
				intent.putExtra("url", text);
				context.startActivity(intent);
			}
		}
	}
    private List<Integer> getPostation(String content, String str) {
		List<Integer> mList = new ArrayList<Integer>();
		if (null != content && null != str) {
			int len = content.length();
			for (int i = 0; i < len; i++) {
				if (str.equals(String.valueOf(content.charAt(i)))) {
					mList.add(i);
				}
			}
		}
		return mList;
	}
    /**
     * Set the size of emojicon in pixels.
     */
    public void setEmojiconSize(int pixels) {
        mEmojiconSize = pixels;
        super.setText(getText());
    }

    /**
     * Set whether to use system default emojicon
     */
    public void setUseSystemDefault(boolean useSystemDefault) {
        mUseSystemDefault = useSystemDefault;
    }
    private int getAvailableWidth()
    {
        return getWidth() - getPaddingLeft() - getPaddingRight();
    }
    private boolean isOverFlowed()
    {
        Paint paint = getPaint();
        float width = paint.measureText(getText().toString());
        if (width > getAvailableWidth()) return true;
        return false;
    }



}
